const router = require('koa-router')(),
  bodyParser = require('koa-bodyparser')();
const read = require('../public/javascripts/start')
const rank = require('../public/javascripts/rank')
// const judgeBind = require('../public/javascripts/back/judgeBind')
const getAuth = require('../public/javascripts/back/getAuth')
const getJsApi = require('../public/javascripts/back/getJsApi')
const error = require('../public/javascripts/error')
const errorget = require('../public/javascripts/errorGet')
const { getQuery, deepCopy } = require('../public/javascripts/common/common')
const { H5 } = require('../public/javascripts/back/variables.js');
const { appid, secret, grant_type2, noncestr, game_url } = H5;

var fs = require('fs'),
  path = require('path');

router.get('/home', async (ctx, next) => {
  // await ctx.render('index', option);
  // read();
  await ctx.render('home', {
    title: '跨区域交通信息资源的共享与交换平台',
    zj: 0,
    sh: 0,
    js: 0,
  });
})
router.get('/clw', async (ctx, next) => {
  await ctx.render('clw', {
    title: '船联网跨省区内河航运数据交换平台',
  });
})
router.get('/boat', async (ctx, next) => {
  await ctx.render('boat', {
    title: '船联网跨省区内河航运数据交换接口及管理系统',
  });
})
router.get('/detect', async (ctx, next) => {
  await ctx.render('detect', {
    title: '消息总线运行监测平台',
  });
})
router.get('/index', async (ctx, next) => {
  await ctx.render('xxzx_home');
})
router.get('/', async (ctx, next) => {
  let cookies = ctx.cookies.get('id');
  if (cookies) ctx.redirect('/h5/index.html');
  else ctx.redirect(`https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx24fe721885ffe295&redirect_uri=http%3A%2F%2Fh5.hituns.io%2Fwx%2Fauth&response_type=code&scope=snsapi_userinfo&state=` + Math.floor(Math.random() * 10000) + `#wechat_redirect`)
})
router.get('/xxzx', async (ctx, next) => {
  await ctx.render('xxzx', {
    title: '消息总线交换统计平台',
  });
})
router.get('/login', async (ctx, next) => {
  await ctx.render('login');
})

router.get('/message', async (ctx, next) => {
  await ctx.render('message', {
    title: '消息总线监控'
  });
})
router.get('/info', async (ctx, next) => {
  await ctx.render('info', {
    title: '消息总线服务器填报'
  });
})

router.post('/error/write', bodyParser, async (ctx, next) => {
  let request = Object.keys(ctx.request.body);
  // console.log(request);
  let req = JSON.parse(request[0])
  let response = await error(req);
  ctx.status = 200;
  ctx.body = response;
})
router.get('/error/get', bodyParser, async (ctx, next) => {
  let response = await errorget();
  ctx.status = 200;
  ctx.body = response;
})

router.get('/json/csj', async (ctx, next) => {
  var csj_copy = JSON.parse(JSON.stringify(global['csj']));
  var length = csj_copy.dates.length - 41;
  csj_copy.dates.splice(0, length)
  csj_copy.values[0].data.splice(0, length)
  csj_copy.values[1].data.splice(0, length)
  csj_copy.values[2].data.splice(0, length)
  ctx.body = csj_copy;
})

router.get('/json/clw', async (ctx, next) => {
  ctx.body = global['clw'];
})

router.get('/json/hituns/:subType', async (ctx, next) => {
  let subType = ctx.params.subType;
  let query = ctx.query;
  let res = null;
  let date = query.date;
  let sum = eval('(' + query.sum + ')');
  if (!date)
    ctx.body = global['hituns'][subType];
  else {
    let startIndex = -1;
    let endIndex = -1;
    let dates = global['hituns'].dates;
    for (let j = 0; j < dates.length; j++) {
      if (dates[j].indexOf(date) != -1) {
        if (startIndex != -1) endIndex = j;
        else startIndex = j;
      }
    }
    if (startIndex == -1) ctx.body = { dates: [], sums: [] };
    else {
      let source_copy = Object.assign({}, global['hituns'][subType]);
      let res = {};
      if (endIndex == -1) endIndex = startIndex;
      if (sum) {
        res = { dates: [], sums: [] };
        for (let k = startIndex; k <= endIndex; k++) {
          res.dates.push(global['hituns'].dates[k]);
          let summary = 0;
          for (var key in source_copy) {
            summary += (source_copy[key][k] * query[key]);
          }
          res.sums.push(summary);
        }
      } else {
        for (var key in source_copy) {
          if (!res[key]) res[key] = [];
          for (let k = startIndex; k <= endIndex; k++) {
            res[key].push(source_copy[key][k] * query[key]);
          }
        }
      }
      ctx.body = res;
    }
  }

})
router.post('/rank/:type', bodyParser, async (ctx, next) => {
  let type = ctx.params.type;
  switch (type) {
    case 'get':
      try {
        let cookies = ctx.cookies.get('id');
        let callback = await rank('get', {}, cookies);
        ctx.body = callback
      } catch (e) {
        console.log(e);
        ctx.body = {
          success: "0",
          content: {},
          error: {
            errorMsg: e
          }
        }
      }
      break;
    case 'set':
      try {
        let request = ctx.request.body;
        let cookies = ctx.cookies.get('id');
        let callback = await rank('set', request, cookies);
        ctx.body = callback
      } catch (e) {
        console.log(e);
        ctx.body = {
          success: "0",
          content: {},
          error: {
            errorMsg: e
          }
        }
      }
      break;
    default:
      ctx.body = {
        success: "0",
        content: {}
      };
      break
  }
})
router.get('/wx/auth/MP_verify_KpbVw8KOVDDtD63y.txt', async (ctx, next) => {
  let txt = fs.readFileSync(path.join(__dirname, '..', '/public/MP_verify_KpbVw8KOVDDtD63y.txt'), 'utf-8');
  ctx.body = txt;
})
router.get('/wx/auth', async (ctx, next) => {
  let code = ctx.query.code,
    state = ctx.query.state;
  var callback = await getAuth(code, ctx, next);
  ctx.cookies.set('id', callback);
  ctx.redirect(game_url);
})
router.get('/wx/getJsApi', async (ctx, next) => {
  var callback = await getJsApi(ctx, next);
  ctx.body = callback;
})
router.get('/ais/get', async (ctx, next) => {
  let ais = deepCopy(global['ais_statistics']);
  let callback = {      //以上四个数据统计并返回
    ais_gps: {},
    ais_static: {},
    ais_gps_ex_re: {},
    ais_static_ex_re: {},
  }
  // try {
  //   ais = JSON.parse(ais);
  // } catch (e) {
  //   ais = callback;
  // }
  delete ais.ais_gps_id;
  delete ais.ais_static_id;
  let { query } = ctx,
    { year, month, day } = query;
  month -= 0
  month < 10 && (month = '0' + month);
  day -= 0
  day < 10 && (day = '0' + day);
  let keyArr = Object.keys(ais.ais_gps);
  if (!year && !month && !day) {
    callback = ais;
  } else {
    keyArr.map(item => {
      let $year = item.split('-')[0],
        $month = item.split('-')[1],
        $day = item.split('-')[2];
      switch (true) {
        case $year == year && month == $month && day == $day:
        case $year == year && !month && !day:
        case $year == year && month == $month && !day:
          callback.ais_gps[item] = ais.ais_gps[item];
          callback.ais_static[item] = ais.ais_static[item];
          callback.ais_gps_ex_re[item] = ais.ais_gps_ex_re[item];
          callback.ais_static_ex_re[item] = ais.ais_static_ex_re[item];
          break;
        default:
          break;
      }
    })
  }
  ctx.body = callback;
})


module.exports = router
